
const {ccclass, property} = cc._decorator;

type textdata = {
    role: number,
    content: string
}
// 建立角色映射
let roleMap = new Map()
roleMap.set(1, { name: '勇者', url:'role/hero' })
roleMap.set(2, { name: '魔王', url:'role/npc' })

@ccclass
export default class Dialog extends cc.Component {

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}
    @property(cc.Sprite)
    picSprite: cc.Sprite
    @property(cc.Label)
    nameLabel: cc.Label
    @property(cc.Label)
    textLabel: cc.Label

    textDataArr: textdata[];  // 文本对话数组

    textIndex: number;  // 当前对话所在数组下标

    nowText:string;
    textEnd:boolean = true;  // 当前文本是否已经播放完毕
    textTime: number = 0;  // 播放总时长

    onLoad () {
        // this.init([
        //     { role: 2, content: '魔王出场了' },
        //     { role: 1, content: '勇者出场了' },
        //     { role: 2, content: '欢迎来到魔王的迷宫，勇者' },
        // ]);
        
        // 初始化键盘输入监听
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this); 
    }
    // 键盘按下事件
    onKeyDown(event: cc.Event.EventKeyboard) {
        switch(event.keyCode) {
            case cc.macro.KEY.space : { this.nextTextData(); break; }
        }
    }
    // 键盘抬起事件
    onKeyUp(event: cc.Event.EventKeyboard) {
    }

    init(textDataArr: textdata[]) {
        this.nowText = null;
        this.textEnd = true;

        this.textIndex = -1;
        this.textDataArr = textDataArr;
        this.node.active = true;  // 显示对话框
        this.nextTextData();
    }
    // 判断执行下一句对话
    nextTextData() {
        // 如果当前没有播放完毕，不执行下一句
        if (!this.textEnd) return ;

        if (++this.textIndex < this.textDataArr.length) {
            // 说明数组中还有对话
            this.setTextData(this.textDataArr[this.textIndex]);
            this.textEnd = false;
        } else {
            // 关闭对话框
            this.closeDialog();
        }
    }
    // 设置当前对话
    setTextData(textdata: textdata) {
        this.nameLabel.string = roleMap.get(textdata.role).name;
        this.textLabel.string = '';
        this.nowText = textdata.content;

        // 加载文件夹下资源
        cc.loader.loadRes(roleMap.get(textdata.role).url, cc.SpriteFrame, (err, texture)=>{
            this.picSprite.spriteFrame = texture;
        })
    }
    // 关闭对话框
    closeDialog() {
        this.node.active = false;
    }
    update (dt) {
        if (!this.nowText) return;
        this.textTime += dt;
        if (this.textTime >= 0.1) {
            if (this.textLabel.string.length < this.nowText.length) {
                // 还要播放
                this.textLabel.string = this.nowText.slice(0, this.textLabel.string.length + 1);
            } else {
                this.textEnd = true; //播放完毕
                this.nowText = '';
            }
            this.textTime = 0;
        }
    }
}
